package com.jp.knowledge.my.activity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.LoginActivity;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.activity.JoinOrgnazitionAcitivity;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.ReviewDetailDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.PersonLogic;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.adapter.OrganizationAdapter;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.my.model.SortCompanyModel;
import com.jp.knowledge.my.resources.OrganizeJoinRes;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.ResultSubscriber;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的组织
 *
 * @author gzejia 978862664@qq.com
 */
public class OrganizeActivity extends SlidingActivity implements View.OnClickListener, ResultSubscriber.OnResultListener, OrganizationAdapter.OrganizationButtonClickListener {

    private static final int GET_ORGANIZE_LIST_CODE = 0x01;
    private static final int SWITCH_ORGANIZE_CODE = 0x02;
    private static final int EXIT_ORGANIZE_CODE = 0x03;
    private static final int JOIN_NEW_ORGANIZE_CODE = 0x04;
    private static final int SORT_ORGANIZE_CODE = 0x05;

    @ViewInject(R.id.organize_none_bg)
    private LinearLayout organizeNoneBg;
    @ViewInject(R.id.current_organize_ll)
    private LinearLayout organizeLl;
    @ViewInject(R.id.current_organize_num_tv)
    private TextView organizeNumTv;
    @ViewInject(R.id.current_organize_rv)
    private RecyclerView organizeRv;
    @ViewInject(R.id.join_more_organize_bn)
    private TextView organizeJoinBn;
    @ViewInject(R.id.join_more_organize_tv)
    private TextView organizeJoinTv;

    private OrganizationAdapter adapter;
    private ItemTouchHelper itemTouchHelper;
    private List<OrganizaModel> organizaModels;

    private CommDialog inputUserNameDialog;
    private CommDialog exitDialog;
    private CommDialog transferPremissionDialog;
    private ReviewDetailDialog reviewDetailDialog;

    private PersonLogic personLogic;
    private LocalBroadCast localBroadCast;
    private LocalBroadcastManager localBroadcastManager;

    @Override
    protected int getResourceId() {
        return R.layout.activity_organize;
    }

    @Override
    protected void init() {
        organizaModels = new ArrayList<>();
        personLogic = new PersonLogic(this);

        organizeRv.setHasFixedSize(true);
        organizeRv.setLayoutManager(new LinearLayoutManager(this));
        adapter = new OrganizationAdapter(this, new ArrayList<OrganizaModel>());
        adapter.setOnSwitchToDefaultListener(this);
        organizeRv.setAdapter(adapter);
        itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                return makeMovementFlags(ItemTouchHelper.DOWN | ItemTouchHelper.UP, 0);
            }
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();
                int toPosition = target.getAdapterPosition();
                OrganizaModel moveOrganize = organizaModels.remove(fromPosition);
                organizaModels.add(toPosition, moveOrganize);
                adapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }
            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {}
            @Override
            public boolean isLongPressDragEnabled() {
//                return adapter.getEditOrganize();
                return false;
            }
        });
        itemTouchHelper.attachToRecyclerView(organizeRv);
        adapter.setItemTouchHelper(itemTouchHelper);

        initDialog();
//        contentView.setBackgroundResource(R.color.gray_bg);
        initTitle();

        organizeJoinBn.setOnClickListener(this);
        initBroadCast();
        getData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == JOIN_NEW_ORGANIZE_CODE && data != null) {
            getData();
        }
    }

    @Override
    protected void onDestroy() {
        localBroadcastManager.unregisterReceiver(localBroadCast);
        super.onDestroy();
    }

    private void initBroadCast(){
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack(){
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                if(LocalBroadCast.COMPANY_JOIN.equals(action)){
                    OrganizaModel organizaModel = (OrganizaModel) intent.getSerializableExtra("joinCompany");
                    int index = intent.getIntExtra("index", 0);
                    if(organizaModel != null)
                        organizaModels.add(index, organizaModel);
                    organizaModels = application.getUserData().getCompanyList();
                    adapter.updateAdapter(organizaModels);
                    setOrganizeView();
                } else if(LocalBroadCast.GET_LOGIN_INFO.equals(action)){
                    getData();
                }
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.COMPANY_JOIN);
        intentFilter.addAction(LocalBroadCast.GET_LOGIN_INFO);
        localBroadcastManager.registerReceiver(localBroadCast, intentFilter);
    }

    private void initTitle(){
        topName.setText("所属组织");
        topDesc.setVisibility(View.GONE);
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        leftIcon.setOnClickListener(this);
        rightIcon.setVisibility(View.VISIBLE);
        rightIcon.setImageResource(R.mipmap.editingcenter);
        rightIcon.setOnClickListener(this);
        rightBtn.setVisibility(View.GONE);
        rightBtn.setText("编辑");
        rightBtn.setOnClickListener(this);
    }

    private void initDialog(){
        inputUserNameDialog = new CommDialog(this);
        inputUserNameDialog.setEditHint("请输入你的姓名");
        inputUserNameDialog.setRightClickDismiss(false);
        inputUserNameDialog.setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inputText = inputUserNameDialog.getEditText();
                if(inputText == null ||  inputText.trim().length() == 0){
                    ToasUtil.toast(OrganizeActivity.this, "请输入有效的用户名");
                } else {
                    application.getUserData().setUsername(inputText);
                    OrganizeActivity.this.onClick(organizeJoinBn);
                    inputUserNameDialog.dismiss();
                }
            }
        });
        exitDialog = new CommDialog(this);
        exitDialog.setRightListener(this);

        transferPremissionDialog = new CommDialog(this);
        transferPremissionDialog.setContent("请转让你的超级管理员权限后才能退出！");
        transferPremissionDialog.setRight("去转让");
        transferPremissionDialog.setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, CompanyAddressBookActivity.class)
                        .putExtra("companyId", organizaModels.get((int)transferPremissionDialog.getTag()).getCompanyId()));
            }
        });

        reviewDetailDialog = new ReviewDetailDialog(mContext);
    }

    private void getData(){
        UserData userData = application.getUserData();
        organizaModels.clear();
        if(userData != null && userData.getCompanyList() != null) {
            List<OrganizaModel> companyList = userData.getCompanyList();
            if(companyList != null && companyList.size() > 0)
                organizaModels.addAll(companyList);
        }
        organizeJoinBn.setVisibility(View.VISIBLE);
        organizeJoinTv.setVisibility(View.GONE);
        setOrganizeView();
        adapter.updateAdapter(organizaModels);
    }

    private void updateData(){
//        loading.show();
//        JsonObject param = new JsonObject();
//        param.addProperty("token", HttpHelper.token);
//        HttpHelper.getInstance(this).getAllOrganiza(param, GET_ORGANIZE_LIST_CODE, this);
        personLogic.getUserData();
    }

    @Override
    public void organizeExit(int organizationPosition) {
        if(organizaModels.get(organizationPosition).getCompanyAdmin() == 1){
            transferPremissionDialog.setTag(organizationPosition);
            transferPremissionDialog.show();
        } else {
            exitDialog.setContent("是否退出\"" + organizaModels.get(organizationPosition).getCompanyName() + "\"？");
            exitDialog.setTag(organizationPosition);
            exitDialog.show();
        }
    }

    @Override
    public void organizeClaim(int position) {
        Intent intent = new Intent(mContext, JoinOrgnazitionAcitivity.class);
        intent.putExtra("company", organizaModels.get(position));
        startActivity(intent);
    }

    @Override
    public void organizeByVip(int position) {
//        startActivity(new Intent(mContext, EnterpriseVipActivity.class)
//                .putExtra("companyId", organizaModels.get(position).getCompanyId()));
        startActivity(new Intent(mContext, ToBeVipOrganize.class)
                .putExtra("position", position));
    }

    @Override
    public void organizeReviewDetail(int position) {
        OrganizaModel organizaModel = organizaModels.get(position);
        try {
            reviewDetailDialog.show(organizaModel.getAuditInfo().get(0).getReason());
        } catch (Exception e){
            reviewDetailDialog.show("");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.icon_left:
                finish();
                break;
            case R.id.join_more_organize_bn:
//                if(userData.getUsername() == null || userData.getUsername().trim().length() == 0) {
//                    ToasUtil.toast(this, "你还未认证用户姓名，请先输入用户姓名");
//                    inputUserNameDialog.show();
//                } else {
//                    startActivity(new Intent(this, SearchListActivity.class)
//                            .putExtra(OrganizeJoinRes.TITLE, "搜索组织"));
//                }
                if(!application.isLogin())
                    startActivity(new Intent(mContext, LoginActivity.class));
                else
                    startActivity(new Intent(this, SearchListActivity.class)
                            .putExtra(OrganizeJoinRes.TITLE, "搜索组织"));
                break;
            case R.id.icon_serach:
            case R.id.right_bn:
                adapter.setEditOrganization(!adapter.getEditOrganize());
                if(adapter.getEditOrganize()) {
                    rightBtn.setText("完成");
                    rightIcon.setVisibility(View.GONE);
                    rightBtn.setVisibility(View.VISIBLE);
                    organizeJoinBn.setVisibility(View.GONE);
                } else {
                    rightBtn.setText("编辑");
                    rightBtn.setVisibility(View.GONE);
                    rightIcon.setVisibility(View.VISIBLE);
                    organizeJoinBn.setVisibility(View.VISIBLE);
                    sortOrganize();
                }
                adapter.updateAdapter(organizaModels);
                setOrganizeView();
                break;
            case R.id.right_btn:
                int organizationPosition = (int)exitDialog.getTag();
                loading.show();
                JsonObject param = new JsonObject();
                param.addProperty("token", HttpHelper.token);
                param.addProperty("type", organizaModels.get(organizationPosition).getCompanyType());
                if(organizaModels.get(organizationPosition).getCompanyType() == 2)
                    param.addProperty("id", organizaModels.get(organizationPosition).getClassId());
                else
                    param.addProperty("id", organizaModels.get(organizationPosition).getCompanyId());
                HttpHelper.getInstance(this).exitOrganiza(param, organizationPosition*10+EXIT_ORGANIZE_CODE, this);

//                OrganizaModel organizaModel = organizaModels.remove(organizationPosition);
////                adapter.notifyItemRemoved(organizationPosition);
//                adapter.updateAdapter(organizaModels);
//                setOrganizeView();
//                localBroadcastManager.sendBroadcast(new Intent(LocalBroadCast.COMPANY_EXIT)
//                        .putExtra("id", "")
//                        .putExtra("companyId", organizaModel.getCompanyId()));
                break;
        }
    }

    /* 组织排序 */
    private void sortOrganize(){
        SortCompanyModel sortCompanyModel = new SortCompanyModel();
        List<SortCompanyModel.OrganizasBean> organizas = new ArrayList<>();
        for(OrganizaModel organizaModel : organizaModels){
            SortCompanyModel.OrganizasBean organizasBean = new SortCompanyModel.OrganizasBean();
            organizasBean.setType(organizaModel.getCompanyType());
            if(organizasBean.getType() == 2)
                organizasBean.setId(organizaModel.getClassId());
            else
                organizasBean.setId(organizaModel.getCompanyId());
            organizas.add(organizasBean);
        }
        sortCompanyModel.setOrganizas(organizas);
        JsonObject param = JsonUtil.getInstance().entityToJson(sortCompanyModel);
        HttpHelper.getInstance(this).sortOrganize(param, SORT_ORGANIZE_CODE, this);

        ArrayList<String> companyIds = new ArrayList<>();
        for(OrganizaModel organizaModel : organizaModels)
            companyIds.add(organizaModel.getCompanyId());
        localBroadcastManager.sendBroadcast(new Intent(LocalBroadCast.COMPANY_SORT)
                .putStringArrayListExtra("companyIds", companyIds));
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        loading.cancel();
        bgLoadingDialog.dismiss();
    }
    @Override
    public void onError(int requestType) {
        if (requestType == GET_ORGANIZE_LIST_CODE) {
            organizeJoinBn.setVisibility(View.VISIBLE);
            organizeJoinTv.setVisibility(View.GONE);
            setOrganizeView();
//            ToasUtil.toast(this, "抱歉，数据获取失败，请稍后重试");
        } else if(requestType%10 == EXIT_ORGANIZE_CODE){
//            ToasUtil.toast(this, "抱歉，组织退出失败，请稍后重试");
        }
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0) {
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
            return;
        }
        if (requestType == GET_ORGANIZE_LIST_CODE) {
            organizaModels = data.getList(OrganizaModel.class);
            organizeJoinBn.setVisibility(View.VISIBLE);
            organizeJoinTv.setVisibility(View.GONE);
//            setOrganizeView();
            application.getUserData().setCompanyList(organizaModels);
            getData();
        } else if(requestType%10 == EXIT_ORGANIZE_CODE){
            localBroadcastManager.sendBroadcast(new Intent(LocalBroadCast.COMPANY_EXIT)
                    .putExtra("companyId", organizaModels.get(requestType/10).getCompanyId()));
            organizaModels.remove(requestType/10);
            setOrganizeView();
        } else if(requestType == SORT_ORGANIZE_CODE){

        }
        application.getUserData().setCompanyList(organizaModels);
        adapter.updateAdapter(organizaModels);
    }

    private void setOrganizeView(){
        UserData userData = application.getUserData();
        int organizeCount = organizaModels.size();
        if (organizeCount > 0) {
            organizeNoneBg.setVisibility(View.GONE);
            organizeLl.setVisibility(View.VISIBLE);
            if(adapter.getEditOrganize())
                rightBtn.setVisibility(View.VISIBLE);
            else
                rightIcon.setVisibility(View.VISIBLE);
            organizeNumTv.setText("你的账号已经加入" + organizeCount + "个组织：");
//            organizeJoinBn.setText("继续加入组织");
            organizeJoinBn.setText("加入组织");
        } else {
            organizeNoneBg.setVisibility(View.VISIBLE);
            organizeLl.setVisibility(View.GONE);
            if(adapter.getEditOrganize())
                rightBtn.setVisibility(View.GONE);
            else
                rightIcon.setVisibility(View.GONE);
            organizeJoinBn.setText("加入组织");
            if(adapter.getEditOrganize())
                onClick(rightBtn);
        }
        if(organizeCount >= 1
                && (userData == null || userData.getIsVip() != 1)
                && !adapter.getEditOrganize())
//            organizeJoinTv.setVisibility(View.VISIBLE);
            organizeJoinTv.setVisibility(View.GONE);
        else
            organizeJoinTv.setVisibility(View.GONE);
    }

    @Override
    public void finish() {
        if(application.getUserData() != null)
            application.getUserData().setCompanyList(organizaModels);    // 将公司数据设置到用户数据中
        updateData();
        setResult(RESULT_OK, getIntent());
        super.finish();
    }
}
